#include "SPI4.h"
#include <stdio.h>


void SPI4_init() {
    uint32_t spix = SPI4;
    uint32_t spix_rcu = RCU_SPI4;
    /************************** GPIO **********************/
    // sclk
    rcu_periph_clock_enable(SPI4_CLK_RCU);
    gpio_mode_set(SPI4_CLK_PORT, GPIO_MODE_AF, GPIO_PUPD_NONE, SPI4_CLK_PIN);
    gpio_output_options_set(SPI4_CLK_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_MAX, SPI4_CLK_PIN);
    gpio_af_set(SPI4_CLK_PORT, SPI4_CLK_AF, SPI4_CLK_PIN);

    // mosi
    rcu_periph_clock_enable(SPI4_MOSI_RCU);
    gpio_mode_set(SPI4_MOSI_PORT, GPIO_MODE_AF, GPIO_PUPD_NONE, SPI4_MOSI_PIN);
    gpio_output_options_set(SPI4_MOSI_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_MAX, SPI4_MOSI_PIN);
    gpio_af_set(SPI4_MOSI_PORT, SPI4_MOSI_AF, SPI4_MOSI_PIN);

    // miso
    rcu_periph_clock_enable(SPI4_MISO_RCU);
    gpio_mode_set(SPI4_MISO_PORT, GPIO_MODE_AF, GPIO_PUPD_NONE, SPI4_MISO_PIN);
    gpio_output_options_set(SPI4_MISO_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_MAX, SPI4_MISO_PIN);
    gpio_af_set(SPI4_MISO_PORT, SPI4_MISO_AF, SPI4_MISO_PIN);
    gpio_bit_set(SPI4_MISO_PORT, SPI4_MISO_PIN);

    /************************** SPI **********************/
    rcu_periph_clock_enable(spix_rcu);
    spi_i2s_deinit(spix);

    spi_parameter_struct sps;
    spi_struct_para_init(&sps);
    sps.device_mode = SPI_MASTER; //设备模式
    sps.frame_size = SPI_FRAMESIZE_8BIT;
    sps.clock_polarity_phase = SPI_CK_PL_LOW_PH_1EDGE;
    sps.nss = SPI_NSS_SOFT;
    sps.prescale = SPI_PSC_32;
    sps.endian = SPI_ENDIAN_MSB;
    spi_init(spix, &sps);
    //spi_nss_internal_high(spix);
    spi_enable(spix);
}

void SPI4_write_byte(uint8_t data) {
    while (RESET == spi_i2s_flag_get(SPI4, SPI_FLAG_TBE)) {};
    spi_i2s_data_transmit(SPI4, data);
    while (RESET == spi_i2s_flag_get(SPI4, SPI_FLAG_RBNE)) {};
    spi_i2s_data_receive(SPI4);
}

uint8_t SPI4_read_byte() {
    while (RESET == spi_i2s_flag_get(SPI4, SPI_FLAG_TBE)) {};
    spi_i2s_data_transmit(SPI4, 0x00);
    while (RESET == spi_i2s_flag_get(SPI4, SPI_FLAG_RBNE)) {};
    return spi_i2s_data_receive(SPI4);
}

/**
 * @desc  : 使用spi读写数据
 * @date  : 2025-02-28
 * @author: AnRui
 * @param :  data - {参数说明}:
 * @return: uint8_t
 * @note  : 为什么先把写放在前面 应为很多硬件 是先传入读取数据的命令 然后才进行读取
 */
uint8_t SPI4_read_write_byte(uint8_t data) {
    while (RESET == spi_i2s_flag_get(SPI4, SPI_FLAG_TBE)) {};
    spi_i2s_data_transmit(SPI4, data);
    while (RESET == spi_i2s_flag_get(SPI4, SPI_FLAG_RBNE)) {};
    return spi_i2s_data_receive(SPI4);
}